

#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>


int Add(MYSQL* mysql)
{
    std::string sql = R"(insert into test_tb values (null, 18, "张三", 91.64);)";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "Query sql failed: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Mod(MYSQL* mysql)
{
    std::string sql = R"(update test_tb set name = "李四" where id = 1;)";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "Query sql failed: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Del(MYSQL* mysql)
{
    std::string sql = R"(delete from test_tb where id = 2;)";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "Query sql failed: " << mysql_error(mysql) << std::endl;
        return -1;
    }
    return 0;
}

int Get(MYSQL* mysql)
{
    std::string sql = R"(select * from test_tb;)";
    int ret = mysql_query(mysql, sql.c_str());
    if (ret != 0)
    {
        std::cout << "Query sql failed: " << mysql_error(mysql) << std::endl;
        return -1;
    }

    MYSQL_RES* res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        std::cout << "Store result failed: " << mysql_error(mysql) << std::endl;
        return -2;
    }
    size_t NumOfRows = mysql_num_rows(res);
    size_t NumOfFields = mysql_num_fields(res);
    for (int i = 0; i < NumOfRows; ++i)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < NumOfFields; ++j)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << std::endl;
    }

    mysql_free_result(res);

    return 0;
}

int main()
{
    // 初始化操作句柄 
    MYSQL* mysql = mysql_init(nullptr);
    if (mysql == nullptr)
    {
        std::cout << "Init mysql failed!" << std::endl;
        return -1;
    }

    // 连接 Mysql 服务器 
    mysql = mysql_real_connect(mysql, "localhost", "exer", "123456", "test_db", 3306, nullptr, 0);
    if (mysql == nullptr)
    {
        std::cout << "Connect mysql server failed!" << std::endl;
        return -2;
    }

    // 设置客户端字符集 
    mysql_set_character_set(mysql, "utf8");

    // 添加数据 
    // Add(mysql);
    // 修改数据 
    // Mod(mysql);
    // 删除数据 
    // Del(mysql);
    // 查询数据 
    Get(mysql);

    // 释放连接 
    mysql_close(mysql);

    return 0;
}